package sfms.controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import sfms.model.User;
import sfms.util.MD5;
import sfms.util.PasswordValidator;
import sfms.view.AdminEditUser;

/**
 * Controller for the main admin window
 * @author amp942
 */
public class Admin implements ControllerBase 
{
    private sfms.view.Admin view;
    private sfms.model.Model model;
    private List<sfms.model.User> users;
    private sfms.model.User user;
    
    /**
     * Initialise a new Admin object
     */
    public Admin(sfms.model.Model model, sfms.model.User user) {
        this.model = model;
        view = new sfms.view.Admin(this);
        this.user = user;
    }
    
    @Override
    public void show() {
        view.setVisible(true);
    }
    
    @Override
    public void hide() {
        view.setVisible(false);
        view.dispose();
    }
    
    /**
     * Create a new user
     */
    public boolean createUser(String username,
            String fname, String sname,
            String role, boolean active, String number,
            String email, java.sql.Date expiry,
            String password) {
        try {
            if (PasswordValidator.validate(password)) {
                String hash = String.valueOf(MD5.encrypt(password.toCharArray()));
                sfms.model.User newUser = new sfms.model.User(username, fname, sname, 
                        email, number, role, active, 
                        expiry, hash);
                if (!model.addUser(newUser)) {
                    JOptionPane.showMessageDialog(null, "The user could not be entered into the database.", "Error", JOptionPane.ERROR_MESSAGE, null);
                }
            } else {
                JOptionPane.showMessageDialog(null, "The password you selected is not secure.", "Error", JOptionPane.ERROR_MESSAGE, null);
                return false;
            }
            return true;
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * Edit/delete a user
     */
    public void editUser(boolean isDeleting, String username) {
        if (isDeleting) {
            //model.deleteUser
        }
        else {
            sfms.model.User selectedUser = model.getUser(username);
            
            AdminEditUser editUser = new AdminEditUser(view, true, this, model, selectedUser);
            editUser.setVisible(true);
        }
    }
        
    /**
     * Log out of the application
     */
    public void logout() {
        sfms.controller.Login login = new sfms.controller.Login(model);
        this.hide();
        login.show();
    }

    //** Hooks **//
    DefaultTableModel modelUsers;

    /**
     * @param model tableUsers.getModel();
     */
    public void setBookingModel(DefaultTableModel model) {
        modelUsers = model;
    }

    public void addUsers() {
        //First remove rows that may be already there.
        int count = modelUsers.getRowCount();
        for (int i = 0; i < count; i++) {
            modelUsers.removeRow(0);
        }

        users = new ArrayList<User>();
        List<User> staff = model.getUsers(User.STAFF);
        List<User> admins = model.getUsers(User.ADMIN);
        if (staff != null) {
            users.addAll(staff);
        }
        if (admins != null) {
            users.addAll(admins);
        }

        if (users != null) {
            for (User u : users) {
                String role = "Administrator";
                if (u.getRole().equals(User.STAFF)) {
                    role = "Staff";
                }

                Object [] data = new Object[] {
                    u.getUsername(),
                    u.getFirstName(),
                    u.getLastName(),
                    u.getEmail(),
                    role,
                    u.getPhoneNumber()
                };

                modelUsers.addRow(data);
            }
        }
    }

    public void addUserRow(User u) {
        Object [] data = new Object[] {
                    u.getUsername(),
                    u.getFirstName(),
                    u.getLastName(),
                    u.getEmail(),
                    u.getRole(),
                    u.getPhoneNumber(),
                    u.isActive()
                };
                
        modelUsers.addRow(data);
    }

    public void updateUser(User user) {
        if (!PasswordValidator.validate(user.getPassword())) {
            JOptionPane.showMessageDialog(null, "Password is not secure.",
                "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            if (model.updateUser(user)) {
                JOptionPane.showMessageDialog(null, "The user was successfully updated.",
                    "Success", JOptionPane.INFORMATION_MESSAGE);                
            }
        }
    }

    public boolean changePassword(String password) { 
        return model.changeUserPassword(user.getUsername(), user.getPassword(), MD5.encrypt(password.toCharArray()));
    }
    
    public ActionListener getDeleteUserListener() {
        return new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae) {
                try{
                    int userRow = view.getUserRow();
                    String username = (String) modelUsers.getValueAt(userRow, 0);
                    
                    String retval = sfms.view.Password.getPassword();
                    System.out.println(retval);
                    
                    String password = sfms.util.MD5.encrypt(retval.toCharArray());
                    System.out.println(password);
                    
                    
                    if (model.getUser(user.getUsername(), password) != null){
                        // Password was good.
                        if (model.removeUser(username)){
                            JOptionPane.showMessageDialog(null, "User deleted.",
                                    "Success", JOptionPane.DEFAULT_OPTION);
                            modelUsers.removeRow(userRow);
                        }
                        else{
                            JOptionPane.showMessageDialog(null, "There was an error deleting the user.",
                                    "Error", JOptionPane.DEFAULT_OPTION);
                        }
                    }
                    else{
                        JOptionPane.showMessageDialog(null, "Password incorrect: no changes made.",
                                "Error", JOptionPane.DEFAULT_OPTION);
                    }                    
                }
                catch (Exception e){
                    System.out.println("No row selected.");
                }
            }  
        };
    }
}